<template>
  <div>
    <el-dialog :width="dialogWidth" :visible.sync="loginDialogVisible" :before-close="closeDialog" center append-to-body>
      <div id="dialog-div">
        <el-container style="margin: 0;padding: 0">
          <el-aside width="50%" height="100%">
            <el-image
                :fit="'scale-down'"
                :src="require('@/assets/logo.png')" ></el-image>
          </el-aside>

          <div style="float:left;margin: 5px;width: 1px;height: 420px; background: darkgray;"></div>
          <el-container width="50%" height="100%">
            <el-header :height="'35px'">
              <el-col :span="12" :offset="9">
                <div style="position: center">
                  <el-radio-group @change="radioGroupChange" v-model="radio">
                    <el-radio-button :label="1">登录</el-radio-button>
                    <el-radio-button :label="2">注册</el-radio-button>
                  </el-radio-group>
                </div>
              </el-col>
            </el-header>

            <el-main>
              <!--使用v-if 和v-else切换不同的form时，要加key来区分！-->
              <div v-if="mode==='login'" style="margin-top: 50px" class="dialog-main" >
                <el-form :model="login_userForm"  ref="login_userForm" key="login_form">
                  <el-form-item label="账号" :label-width="formLabelWidth" style="margin-bottom: 50px">
                    <el-col :span="22">
                      <el-input placeholder="用户名/手机号" v-model="login_userForm.account" clearable width="200px" type="text"></el-input>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="密码" :label-width="formLabelWidth" key="login_password">
                    <el-col :span="22">
                      <el-input v-model="login_userForm.password" show-password></el-input>
                    </el-col>
                  </el-form-item>
                </el-form>
              </div>

              <div v-else style="margin-top: 10px" class="dialog-main">
                <el-form :model="signUp_userForm" :rules="signUp_userRules" ref="signUp_userForm" key="signup_form">
                  <el-form-item label="用户名" :label-width="formLabelWidth" prop="nickname" >
                    <el-col :span="24">
                      <el-input placeholder="不超过10位的汉字字母数字组合" v-model="signUp_userForm.nickname" clearable></el-input>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="手机号" :label-width="formLabelWidth" prop="telephone" >
                    <el-col :span="24">
                      <el-input placeholder="仅支持中国大陆手机号" v-model="signUp_userForm.telephone" clearable></el-input>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="验证码" :label-width="formLabelWidth" prop="verifyCode" >
                    <el-col :span="12">
                      <el-input placeholder="4位有效数字" v-model="signUp_userForm.verifyCode" clearable></el-input>
                    </el-col>
                    <el-button style="margin-left: 18px"  :disabled="btnSendDisable" @click="sendVerifyCode">{{btnSendText}}</el-button>
                  </el-form-item>
                  <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
                    <el-col :span="24">
                      <el-input placeholder="至少为8位数字和字母的组合" v-model="signUp_userForm.password" show-password></el-input>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="确认密码" :label-width="formLabelWidth" prop="confirmPwd">
                    <el-col :span="24">
                      <el-input placeholder="至少为8位数字和字母的组合" v-model="signUp_userForm.confirmPwd" show-password></el-input>
                    </el-col>
                  </el-form-item>
                </el-form>
              </div>
              <div  class="dialog-footer" style="margin-top: 40px">
                <el-col :span="20" :offset="2"  >
                  <span>
                      <el-button @click="resetForm('signUp_userForm')" style="margin-left: 65px" >取 消</el-button>
                      <el-button v-if="mode==='login'" type="primary" @click="loginSubmit" style="margin-left: 90px">登 录</el-button>
                      <el-button v-else type="primary" @click="signUpSubmit('signUp_userForm')" style="margin-left: 90px">注 册</el-button>
                  </span>
                </el-col>
              </div>
            </el-main>

          </el-container>
        </el-container>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {AxiosNetwork} from "../../plugins/axios";
import {userOptionMap} from "./userOptionMap";
export default {
  name: "LoginDialog",
  //双向绑定数据
  data(){
    //验证昵称是否冲突
    let checkNickName = (rule,value,callback)=>{
      AxiosNetwork('GET','/user/signup',
          {
            zrNickname:value
          },null,
          res=>{
            let optionResult = res.data
            console.log(optionResult)
            if (optionResult.status){
              return callback()
            }else {
              return callback(new Error(userOptionMap.get(optionResult.message)))
            }
          },err=>{
            console.log(err)
            return callback(new Error("网络拥堵"))
          })
    }

    //验证电话是否合法以及被注册过
    let checkTelephone=(rule,value,callback)=>{
      const regMobile = /^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(16[5,6])|(17[0-8])|(18[0-9])|(19[1,5,8,9]))\d{8}$/
      console.log("电话="+value)
      //是电话号码
      if (regMobile.test(value)){
        AxiosNetwork('GET','/user/signup',
            {
             zrTelephone:value
            },null,
        res=>{
            let optionResult = res.data
            if (optionResult.status){
              return callback()
            }else {
              return  callback(new Error(userOptionMap.get(optionResult.message)))
            }
        },err=>{

            })
      }else {
        return callback(new Error('请输入合法的手机号'))
      }
    }

    //检验验证码
    let checkVerifyCode=(rule,value,callback)=>{
      //todo 后台检查验证码

    }

    //检验两次密码是否一致
    let checkConfirmPassword=(rule,value,callback)=>{
      if (value===""){
        callback(new Error("请确认密码"))
      }else if (value!==this.signUp_userForm.password){
        callback(new Error("两次输入密码不一致"))
      }else {
        callback()
      }
    }
    return{
      login_userForm:{
        account:'',
        password:''
      },
      signUp_userForm:{
        nickname:'',
        telephone:'',
        verifyCode:'',
        password:'',
        confirmPwd:''
      },
      signUp_userRules:{
        nickname:[
          {required:true,message:'请输入昵称',trigger:'blur'},
          {min:1,max:10,message: '长度为1-10的数字汉字字母组合',trigger: 'blur'},
          {validator:checkNickName,trigger: 'blur'}
        ],
        telephone: [
          {required:true,message:'请输入电话号码',trigger:'blur'},
          {validator:checkTelephone,trigger: 'blur'}
        ],
        verifyCode: [
          {required:true,message:'请输入验证码',trigger:'blur'}
        ],
        password:[
          {required:true,message:'请输入密码',trigger:'blur'},
          {min:6,max:18,message: '长度为6-18数字字母组合',trigger: 'blur'}
        ],
        confirmPwd: [
          {required:true,validator:checkConfirmPassword,trigger:'blur'}
        ]

      },
      radio:1,
      mode:'login',
      formLabelWidth:'80px',
      loginDialogVisible:false,
      dialogWidth: '',
      btnSendText:'发送验证码',
      btnSendDisable:false,
      btnDisableTime:60,
      btnSendClock:null,
      userOptionResult:{
        status:false,
        option:0,
        result:null,
        message:0
      },

      userOptionMap: userOptionMap

    }
  },
  //用于父子组件通信
  props:{
    openDialog:false
  },
  //监视器
  watch:{
    openDialog(val){
      console.log("openDialog="+val)
      this.loginDialogVisible =val
    },

  },
  methods:{
    /**
     *以下函数与ui相关
     */
    //登录/注册切换
    radioGroupChange(val){
      if (val===1){
        this.mode='login'
      }else {
        this.mode='signup'
      }
      console.log(this.radio)
    },

    //关闭登录框
    closeDialog(){
      this.resetForm()
      this.loginDialogVisible = false;
      // this.$store.commit('syncUpdateLoginStatus',false)
      this.$emit('closeDialog')
    },

    //重置input
    resetForm(formName){
      // if (this.$refs[formName]!==undefined){
      //   this.$refs[formName].resetFields();
      // }
      // this.$refs.signUp_userForm.resetFields()
      if (this.radio===1){
        this.$refs.login_userForm.resetFields()
      }else {
        this.$refs.signUp_userForm.resetFields()
      }

    },

    //动态设置登录框宽度
    setDialogWidth(){
      const defaultWidth = 950
      let screenWidth = document.body.clientWidth
      if (screenWidth<defaultWidth){
        this.dialogWidth = '100%'
      }else {
        this.dialogWidth = ((defaultWidth/screenWidth)*100).toFixed(1)+"%"
      }
      console.log('dialogWith='+this.dialogWidth)
    },

    //更新验证码时间
    updateClock(){
      this.btnDisableTime--
      if (this.btnDisableTime>0){
        this.btnSendText = this.btnDisableTime +"秒"
      }else {
        clearInterval(this.btnSendClock)
        this.btnDisableTime = 60
        this.btnSendDisable = false
        this.btnSendText = "重新发送"
      }
    },

    /**
     * 以下函数与network相关
     */
    //todo 发送验证码
    sendVerifyCode(){
      //todo 向后台发送请求
      this.btnSendDisable = true
      this.btnSendClock =setInterval(this.updateClock,1000)
    },

    //todo 注册
    signUpSubmit(formName){
      this.$refs[formName].validate(async (valid)=>{
        if (valid){
          alert('submit!');
        }else {
          console.log('error submit!')
          return false
        }
      })
    },

    //登录
    loginSubmit(){
      let loginParams = JSON.stringify(this.login_userForm)
      console.log(loginParams+"loginParams");
      AxiosNetwork('GET','/user/login',
          {
            account:this.login_userForm.account,
            password:this.login_userForm.password
          },
          null,
          res=>{
            let optionResult = res.data
            //登录成功
            if (optionResult.status===true){
              console.log(optionResult.result)
              this.$store.commit("syncUpdateUser",optionResult.result)
              this.$store.commit('syncUpdateLoginStatus',true)
              this.closeDialog()
              this.$parent.$parent.openNotification()
            }else {
              //登录失败
              console.log(optionResult.message)
            }
          },err=>{
            console.log(err)
          })
    },
  },
  mounted() {
    //监听屏幕宽度变化
    window.onresize = ()=>{
      return(()=>{
        this.setDialogWidth()
          }
      )()
    }
  },
  created() {
    console.log("windowWidth初始化")
    this.setDialogWidth()
    this.userOptionMap.set("","")
  },
}
</script>

<style scoped>
  .dialog-main{
    margin-left: 0;
  }
  #dialog-div{
    height: 455px;
    overflow: auto;
  }
</style>